<?php
/**
 * Framework_OpenID_Server
 *
 * @author      Ian Szewczyk <roamzero@gmail.com>
 * @copyright   (c) 2007 Ian Szewczyk. All rights reserved.
 * @license     http://www.opensource.org/licenses/bsd-license.php
 * @package OpenID
 * @filesource
 */

require_once 'Auth/OpenID/Server.php';

/**
 * Framework_OpenID_Server
 *
 * This is the base class for user related functions
 *
 * @author Ian Szewczyk <roamzero@gmail.com>
 * @package OpenID
 */
class Framework_OpenID_Server extends Framework_Object
{

	/**
     * $store
     *
     * @access      private
     * @var         object		$store      OpenID store
     */
	private $store;

	/**
     * $server
     *
     * @access      private
     * @var         object		$server     OpenID server
     */
	private $server;

	/**
     * $request
     *
     * @access      private
     * @var         object		$request     OpenID request object
     */
	private $request;

	/**
     * $respons
     *
     * @access      private
     * @var         object		$response    OpenID response object
     */
	private $response;

	/**
     * $session
     *
     * @access      private
     * @var         object		$session    Framework_Session object
     */
	private $session;

	/**
     * __construct
     *
	 * @access 		public
     * @param		string		$store		The kind of store to use
     * @return 		void
     */
	public function __construct($store = 'db')
	{
		parent::__construct();

		// Setup the store
		switch (true) {
			case $store == 'db':
				require_once 'Auth/OpenID/MySQLStore.php';
				$this->store = new Auth_OpenID_MySQLStore(Framework_DB::getDBConnection());
				$this->store->createTables();
				break;
		}

		// Setup the server
		$this->server = new Auth_OpenID_Server($this->store);
			
			
		// Check server
		if ($this->server instanceof Auth_OpenID_ServerError) {
			throw new Framework_Exception(PEAR::raiseError($this->server->toString()));
		}

	}

	/**
     * start
     *
	 * @access 		public
     * @param		object		$request		OpenID request object
     * @return 		mixed 		void, PEAR_Error on failure
     */
	public function start($request = null)
	{

		if (!$request) {

			// Setup the request object
			$method = $_SERVER['REQUEST_METHOD'];
			$request = null;
			if ($method == 'GET') {
				$request = $_GET;
			} else {
				$request = $_POST;
			}
			// No request
			if (!$request) {
				return PEAR::raiseError('Missing Request Parameters');
			}

				

			// Make request
			//$request = Auth_OpenID::fixArgs($request);
			$this->request = $this->server->decodeRequest();
				
		} else {
			$this->request = $request;
		}


		// Check request
		if ($this->request instanceof Auth_OpenID_ServerError) {
			return PEAR::raiseError($this->request->toString());
		}

		// Load the request into the session
		$this->session = Framework_Session::singleton();
		$this->session->openIDRequest = $this->request;
	}

	/**
     * start
     *
	 * @access 		public
     * @return 		boolean
     */
	public function doAuth()
	{
		
		$userIdentity = Framework_OpenID::getIdentity();

		if (in_array($this->request->mode, array('checkid_immediate', 'checkid_setup'))) {
			
			if ($this->request->identity == $userIdentity) {
				
				$response = $this->request->answer(true);
				
				// Add peopletab
				$peopletab = $this->getPeopletab();
				if (is_array($peopletab)) {
					foreach ($peopletab as $k => $v) {
						$response->fields->setArg('http://peopletab.com/-/protocol/0', $k, $v);
					}
				}
				
				$this->response = $response;
				$this->session->openIDRequest = null;
				
				return true;

			} else if ($this->request->immediate) {
				$session->openIDRequest = null;
				$this->response = $this->request->answer(false, $this->getServerURL());
				$this->generateResponse();
					
			} else {
				// Not Logged in, must redirect to login page
				return false;
			}
		} else {
				
			$this->response = $this->server->handleRequest($this->request);
			$this->generateResponse();
		}


	}

	/**
     * generateResponse
     *
	 * @access 		public
     * @return 		void
     */
	public function generateResponse()
	{
		$webResponse = $this->server->encodeResponse($this->response);
		// Apply header
		foreach ($webResponse->headers as $k => $v) {
			header("$k: $v");
		}

		// Close header
		//header(header_connection_close);
		print $webResponse->body;
		exit(0);
	}

	/**
     * getServerURL
     *
	 * @access 		public
     * @return 		string
     */
	public function getServerURL()
	{
		$path = $_SERVER['SCRIPT_NAME'];
		$host = $_SERVER['HTTP_HOST'];
		$port = $_SERVER['SERVER_PORT'];
		$s = $_SERVER['HTTPS'] ? 's' : '';
		if (($s && $port == "443") || (!$s && $port == "80")) {
			$p = '';
		} else {
			$p = ':' . $port;
		}

		return "http$s://$host$p$path";

	}

	/**
     * setRequestInfo
     *
     * @access 		public
	 * @param		object		$request		OpenID request object
     * @return 		void
     */
	public function setRequestInfo($request=null)
	{
		if (!isset($request)) {
			unset($_SESSION['request']);
		} else {
			$_SESSION['request'] = serialize($request);
		}
	}


	private function getSreg()
	{

	}

	/**
     * getPeopletab
     *
     * @access 		private
     * @return 		array
     */
	private function getPeopletab()
	{
		$user = Framework_User::singleton();
		$peopletab = array();

		$peopletab['userName'] = $user->userName;
		$peopletab['blurb'] = $user->blurb;
		$peopletab['siteDomain'] = $user->siteDomain;
		$peopletab['avatarURL'] = $user->avatarURL;
		$peopletab['publicKey'] = $user->publicKey;

		return $peopletab;
	}


}

?>